package com.example.demo.utils;

import com.example.demo.domain.User;

import java.util.HashMap;

/**
 * @author WaterTiger
 * @since 2020/6
 */
public class UserUtil {
    /**
     * cache
     */
    private static int capacity = 0;
    private static HashMap<Integer, Integer> logCount;
    private static HashMap<Integer, User> userCache;

    public void init(){
        capacity = 0;
        logCount = new HashMap<Integer, Integer>();
        userCache = new HashMap<Integer, User>();
    }

    public void updateCount(User user){
        // update count
        int id = user.getId();
        Integer count = logCount.get(id);
        count = (count == null) ? 1 : count + 1;
        logCount.put(id, count);

        // if count >= 3, need to add user info to cache
        if(count >= 3){
            addCache(user);
        }
    }

    //when capacity > 5, clear cache
    public void addCache(User user){
        userCache.put(user.getId(), user);
        capacity++;
        if(capacity > 5){
            init();
            logCount.put(user.getId(),3);
            userCache.put(user.getId(), user);
            capacity++;
        }
    }

    /**
     * <p>
     * tips: need to user this function when any user is changed !
     * but if user cache doesn't contain the user, the action of update is unnecessary
     * </p>
     * @param user : the user who need to update
     */
    public void updateCache(User user){
        int id = user.getId();
        if(userCache.get(id) != null){
            userCache.put(id, user);
        }
    }

    public void deleteCache(int id){
        if(userCache.get(id) != null){
            userCache.remove(id);
        }
    }

    public User getCache(int id){
        if(userCache.get(id) != null){
            return userCache.get(id);
        }
        else{
            return null;
        }
    }
}
